package com.badibadi.activity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.badibadi.abcpinying.CharacterParser;
import com.badibadi.abcpinying.PinyinComparator;
import com.badibadi.abcpinying.SeeOtherPeopleAdapter;
import com.badibadi.abcpinying.SideBar;
import com.badibadi.abcpinying.SortModel;
import com.badibadi.abcpinying.SideBar.OnTouchingLetterChangedListener;
import com.badibadi.infos.Record_Info_Model_2;
import com.badibadi.infos.Results;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
//import com.badibadi.uniclubber.SeeOtherPeopleSpaceActivity;
import com.badibadi.uniclubber.R.layout;
import com.badibadi.uniclubber.R.menu;
import com.libjph.util.StringUtil;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/**
 * 看记录参加者 2014-11-11
 * 
 * @author Administrator
 * 
 */
public class PinyinSeeRecordParticipantsActivity extends BaseActivity {

	private String TAG = "PinyinSeeOtherPeopleFriendActivity";
	private ListView sortListView;
	private SideBar sideBar;
	private TextView dialog, title;
	private SeeOtherPeopleAdapter adapter;
	/**
	 * 汉字转换成拼音的类
	 */
	private CharacterParser characterParser;
	private List<SortModel> SourceDateList;
	private List<SortModel> List;
	// 从上个界面中传入的
	List<Record_Info_Model_2> info;

	private String pageNum = "9999";
	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinComparator pinyinComparator;
	/**
	 * 被看人
	 */
	private String uid = "1";
	/**
	 * 查看者
	 */
	private String fid = "-1";

	private int page = 1;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(PinyinSeeRecordParticipantsActivity.this);
				try {
					Utils.showMessage(PinyinSeeRecordParticipantsActivity.this,
							getResources().getString(R.string.l_net_error));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 2:
				Utils.ExitPrgress(PinyinSeeRecordParticipantsActivity.this);
				try {
					initViews();
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 3:
				Utils.ExitPrgress(PinyinSeeRecordParticipantsActivity.this);
				// onLoad();
				try {
					Utils.showMessage(PinyinSeeRecordParticipantsActivity.this,
							getResources().getString(R.string.l_xa10));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 4:
				Utils.ExitPrgress(PinyinSeeRecordParticipantsActivity.this);
				try {
					// Utils.showMessage(PinyinSeeOtherPeopleFriendActivity.this,
					// results2.getRetmsg());
				} catch (Exception e) {
					// TODO: handle exception
				}
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		goToTheTitle();
		setContentView(R.layout.activity_see_other_people_friend);

		init();
		// initViews();
	}

	private void init() {
		// TODO Auto-generated method stub
		this.findViewById(R.id.return_btn).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						PinyinSeeRecordParticipantsActivity.this.finish();
					}
				});

		// intent.putExtra("info", (Serializable)info);

		info = (List<Record_Info_Model_2>) getIntent().getSerializableExtra(
				"info");
		title = (TextView) findViewById(R.id.title);
		title.setText(getResources().getString(R.string.l_xb131));
		// is_firend

		// for(int i=0;i<SourceDateList.size();i++)
		// {
		// SourceDateList.get(i).setIs_firend("1");
		// }
		// String id = getIntent().getStringExtra("uid");
		// if (!StringUtil.isNullOrEmpty(id)) {
		// uid = id;
		// }
		// String fid2 = getIntent().getStringExtra("fid");
		// if (!StringUtil.isNullOrEmpty(id)) {
		// fid = fid2;
		// }
		// initInterNet();
		initViews();
	}

	private void initInterNet() {
		// TODO Auto-generated method stub
		Utils.showPrgress(PinyinSeeRecordParticipantsActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				List = new ArrayList<SortModel>();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("uid", uid);
//				   
				map.put("fid", fid);
				map.put("page", 1);
				map.put("pageNum", pageNum);
				String invite_content = Utils.getRequest(Constants.BadiUrl
						+ "friends?uid=" + uid + "&page=" + 1 + "&pageNum="
						+ pageNum);
				//    
				if (invite_content != null) {

					Results results = Utils.checkResult_NNN(
							PinyinSeeRecordParticipantsActivity.this,
							invite_content);
					if (results != null && !results.getRetmsg().equals("null")) {
//						   
						try {
							List = JSONUtils.getListByJsonString(
									results.getRetmsg(), SortModel.class);
							// mList.addAll(list);

							mHandler.sendEmptyMessage(2);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						mHandler.sendEmptyMessage(3);
					}
				} else {

					mHandler.sendEmptyMessage(1);
				}

			}
		});
	}

	private void initViews() {
		// 实例化汉字转拼音类
		characterParser = CharacterParser.getInstance();
		pinyinComparator = new PinyinComparator();
		sideBar = (SideBar) findViewById(R.id.sidrbar);
		dialog = (TextView) findViewById(R.id.dialog);
		sideBar.setTextView(dialog);

		// 设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
				int position = adapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					sortListView.setSelection(position);

				}

			}
		});
		sortListView = (ListView) findViewById(R.id.country_lvcountry);
		sortListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 这里要利用adapter.getItem(position)来获取当前position所对应的对象
				// Toast.makeText(getApplication(),
				// ((SortModel) adapter.getItem(position)).getNickName(),
				// Toast.LENGTH_SHORT).show();
				Intent intent = new Intent(
						PinyinSeeRecordParticipantsActivity.this,
						SeeOtherPeopleSpaceActivity.class);
				intent.putExtra("friend_id",
						((SortModel) adapter.getItem(position)).getId());
				startActivity(intent);
			}
		});
		// TODO Auto-generated method stub

		initData();
		// 根据a-z进行排序源数据
		Collections.sort(SourceDateList, pinyinComparator);
		adapter = new SeeOtherPeopleAdapter(this, SourceDateList);
		sortListView.setAdapter(adapter);

	}

	protected void initData() {
		// 对数据进行过滤操作，把相同id的过滤掉
		List<Record_Info_Model_2> infos = new ArrayList<Record_Info_Model_2>();
		Set<Integer> set = new HashSet<Integer>();
		for (int i = 0; i < info.size(); i++) {
			if (info.get(i).getId() != null)
				set.add(Integer.parseInt(info.get(i).getId()));
		}
		//    

		Iterator i1 = set.iterator();
		while (i1.hasNext()) {
			Integer temp = (Integer) i1.next();
			//    
			// infos.add(info.get(temp));

			for (int i = 0; i < info.size(); i++) {
				if (("" + info.get(i).getId()).equals("" + temp)) {
					infos.add(info.get(i));
					break;
				}
			}
		}

		// 更新了数据
		SourceDateList = filledData(infos);
	}

	/**
	 * 为ListView填充数据
	 * 
	 * @param date
	 * @return
	 */
	private List<SortModel> filledData(List<Record_Info_Model_2> date) {
		List<SortModel> mSortList = new ArrayList<SortModel>();
		for (int i = 0; i < date.size(); i++) {
			SortModel sortModel = new SortModel();
			sortModel.setNickName(date.get(i).getNickName());
			sortModel.setHead(date.get(i).getHead());
			sortModel.setId(date.get(i).getId());
			// sortModel.setMotto(date.get(i).getMotto());
			sortModel.setIs_firend(date.get(i).getIs_firend());

			// 汉字转换成拼音
			String pinyin = characterParser.getSelling(""
					+ date.get(i).getNickName());
//			   
			String sortString = pinyin.substring(0, 1).toUpperCase();

			// 正则表达式，判断首字母是否是英文字母
			if (sortString.matches("[A-Z]")) {
				sortModel.setSortLetters(sortString.toUpperCase());
			} else {
				sortModel.setSortLetters("#");
			}

			sortModel.setMotto("这只是一项测试");

			mSortList.add(sortModel);
		}
		return mSortList;

	}

	/**
	 * 根据输入框中的值来过滤数据并更新ListView
	 * 
	 * @param filterStr
	 */
	private void filterData(String filterStr) {
		List<SortModel> filterDateList = new ArrayList<SortModel>();
		// 是否为空
		if (TextUtils.isEmpty(filterStr)) {
			filterDateList = SourceDateList;
		} else {
			filterDateList.clear();
			for (SortModel sortModel : SourceDateList) {
				String name = sortModel.getNickName();
				if (name.indexOf(filterStr.toString()) != -1
						|| characterParser.getSelling(name).startsWith(
								filterStr.toString())) {
					filterDateList.add(sortModel);
				}
			}
		}

		// 根据a-z进行排序
		Collections.sort(filterDateList, pinyinComparator);
		adapter.updateListView(filterDateList);
	}

	public SeeOtherPeopleAdapter getAdapter() {
		return adapter;
	}

	public void setAdapter(SeeOtherPeopleAdapter adapter) {
		this.adapter = adapter;
	}

	// /**
	// * 选择组员
	// *
	// * @author Administrator
	// *
	// */
	// public class ChoiceCrewAdapter extends BaseExpandableListAdapter {
	//
	// public String[] ABC = { "A", "C" };
	//
	// @Override
	// public int getGroupCount() {
	// // TODO Auto-generated method stub
	// return ABC.length;
	// }
	//
	// @Override
	// public View getGroupView(int groupPosition, boolean isExpanded,
	// View convertView, ViewGroup parent) {
	// // TODO Auto-generated method stub
	// TextView atv = new TextView(ChoiceCrewActivity.this);
	// atv.setText("" + ABC[groupPosition]);
	// return atv;
	// }
	//
	// @Override
	// public int getChildrenCount(int groupPosition) {
	// // TODO Auto-generated method stub
	// return 10;
	// }
	//
	// @Override
	// public View getChildView(int groupPosition, int childPosition,
	// boolean isLastChild, View convertView, ViewGroup parent) {
	// // TODO Auto-generated method stub
	// LayoutInflater inflater = LayoutInflater
	// .from(ChoiceCrewActivity.this);
	// convertView = inflater.inflate(R.layout.choice_crew_import_layout,
	// null);
	//
	// return convertView;
	// }
	//
	// @Override
	// public Object getChild(int groupPosition, int childPosition) {
	// // TODO Auto-generated method stub
	// return null;
	// }
	//
	// @Override
	// public long getChildId(int groupPosition, int childPosition) {
	// // TODO Auto-generated method stub
	// return 0;
	// }
	//
	// @Override
	// public Object getGroup(int groupPosition) {
	// // TODO Auto-generated method stub
	// return null;
	// }
	//
	// @Override
	// public long getGroupId(int groupPosition) {
	// // TODO Auto-generated method stub
	// return 0;
	// }
	//
	// @Override
	// public boolean hasStableIds() {
	// // TODO Auto-generated method stub
	// return false;
	// }
	//
	// @Override
	// public boolean isChildSelectable(int groupPosition, int childPosition) {
	// // TODO Auto-generated method stub
	// return false;
	// }
	//
	// }
}
